package com.example.myapplication1;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class DBManager {
    private DBHelper dbHelper;
    private String TB_NAME;
    private String TB_LAST_UPDATE = "tb_last_update"; // 新增的最后更新时间表名

    public DBManager(Context context) {
        dbHelper = new DBHelper(context);
        TB_NAME = DBHelper.TB_NAME;
        // 确保最后更新时间表存在
        ensureLastUpdateTableExists();
    }

    // 创建最后更新时间表（如果不存在）
    private void ensureLastUpdateTableExists() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TB_LAST_UPDATE +
                "(ID INTEGER PRIMARY KEY, LAST_UPDATE LONG)");
        db.close();
    }

    // 获取最后更新时间（毫秒时间戳）
    public long getLastUpdateTime() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        long time = 0;
        Cursor cursor = db.query(TB_LAST_UPDATE,
                new String[]{"LAST_UPDATE"},
                "ID=?",
                new String[]{"1"},
                null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            time = cursor.getLong(0);
            cursor.close();
        }
        db.close();
        return time;
    }

    // 设置最后更新时间（当前时间）
    public void setLastUpdateTime() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("ID", 1);
        values.put("LAST_UPDATE", System.currentTimeMillis());
        db.insertWithOnConflict(TB_LAST_UPDATE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
    }

    // 检查今天是否已经更新过
    public boolean isTodayUpdated() {
        long lastUpdate = getLastUpdateTime();
        if (lastUpdate == 0) return false; // 从未更新过

        Calendar lastCal = Calendar.getInstance();
        lastCal.setTimeInMillis(lastUpdate);

        Calendar todayCal = Calendar.getInstance();

        return lastCal.get(Calendar.YEAR) == todayCal.get(Calendar.YEAR) &&
                lastCal.get(Calendar.MONTH) == todayCal.get(Calendar.MONTH) &&
                lastCal.get(Calendar.DAY_OF_MONTH) == todayCal.get(Calendar.DAY_OF_MONTH);
    }

    // 以下是原有的数据库操作方法（保持不变）
    public void add(RateItem item) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("curname", item.getCurName());
        values.put("currate", item.getCurRate());
        db.insert(TB_NAME, null, values);
        db.close();
    }

    public void addAll(List<RateItem> list) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        for (RateItem item : list) {
            ContentValues values = new ContentValues();
            values.put("curname", item.getCurName());
            values.put("currate", item.getCurRate());
            db.insert(TB_NAME, null, values);
        }
        db.close();
    }

    public void deleteAll() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(TB_NAME, null, null);
        db.close();
    }

    public void delete(int id) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(TB_NAME, "ID=?", new String[]{String.valueOf(id)});
        db.close();
    }

    public void update(RateItem item) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("curname", item.getCurName());
        values.put("currate", item.getCurRate());
        db.update(TB_NAME, values, "ID=?", new String[]{String.valueOf(item.getId())});
        db.close();
    }

    @SuppressLint("Range")
    public List<RateItem> listAll() {
        List<RateItem> ratelist = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(TB_NAME, null, null, null, null, null, null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                RateItem item = new RateItem();
                item.setId(cursor.getInt(cursor.getColumnIndex("ID")));
                item.setCurName(cursor.getString(cursor.getColumnIndex("CURNAME")));
                item.setCurRate(cursor.getString(cursor.getColumnIndex("CURRATE")));
                ratelist.add(item);
            }
            cursor.close();
        }
        db.close();
        return ratelist;
    }

    @SuppressLint("Range")
    public RateItem findById(int id) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(TB_NAME, null, "ID=?", new String[]{String.valueOf(id)}, null, null, null);
        RateItem rateItem = null;
        if (cursor != null && cursor.moveToFirst()) {
            rateItem = new RateItem();
            rateItem.setId(cursor.getInt(cursor.getColumnIndex("ID")));
            rateItem.setCurName(cursor.getString(cursor.getColumnIndex("CURNAME")));
            rateItem.setCurRate(cursor.getString(cursor.getColumnIndex("CURRATE")));
            cursor.close();
        }
        db.close();
        return rateItem;
    }
}